package query;




import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import document.InvertedIndex;
import query.ExpandQuery;

import edu.smu.tspell.wordnet.*;



public class QueryLibrary {
	protected Vector<Query> queries;
	
	public QueryLibrary() {
		queries = new Vector<Query>();
	}
	
	public void initializeFrom(String folderPath) {
		
		File directory = new File(folderPath);
		File files[] = directory.listFiles();
		
		
		for (File f:files) 
		{
			if(!f.isDirectory())
			{

			StringBuffer content = new StringBuffer();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(f));
				String line = "";

				while ((line = reader.readLine()) != null) {

					content.append(line).append(System.getProperty("line.separator"));

				}
				reader.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			buildQuery(content.toString());
			
			}
			
		}
	}

	public void initializeWithSynset(String folderPath) {

		File directory = new File(folderPath);
		File files[] = directory.listFiles();
		ExpandQuery expander = new ExpandQuery();

		for (File f:files)
		{
			if(!f.isDirectory())
			{

			StringBuffer content = new StringBuffer();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(f));
				String line = "";
                                String expanded_query = "";

				while ((line = reader.readLine()) != null) {
                                        expanded_query = expander.expand(line);

					content.append(expanded_query).append(System.getProperty("line.separator"));

				}
				reader.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			buildQuery(content.toString());

			}

		}

	}


	
	protected void buildQuery(String content)
	{
		QueryBuilder qb = new QueryBuilder();
		qb.parse(content);
		queries.add(qb.getQuery());
	}
	
	public void processAll(InvertedIndex index) {
		for (Query query : queries) {
			long startTime = System.nanoTime();
			query.process(index);
			long endTime = System.nanoTime();
			float totalTime = (float) ((endTime-startTime)/1000000.0);
			System.out.println(query.getName() + "(" + totalTime + "ms)"); 
			System.out.println(index.toDocNames(query.getResult()).toString());
		}
	}
}
